package com.witframework.util;

public class ObjectConverter{
  public static <T> T convertObject(Class<T> parameterClass, Object value){
    Object newValue = value;
    if (value != null){
      if (!(parameterClass.isAssignableFrom(value.getClass())))
        if (parameterClass.isAssignableFrom(String.class)) {
          newValue = value.toString();
        } else if ((parameterClass.isAssignableFrom(Integer.TYPE)) || (parameterClass.isAssignableFrom(Integer.class))) {
          newValue = new Integer(value.toString());
        } else if ((parameterClass.isAssignableFrom(Short.TYPE)) || (parameterClass.isAssignableFrom(Short.class))) {
          newValue = new Short(value.toString());
        } else if ((parameterClass.isAssignableFrom(Long.TYPE)) || (parameterClass.isAssignableFrom(Long.class))) {
          newValue = new Long(value.toString());
        } else if ((parameterClass.isAssignableFrom(Float.TYPE)) || (parameterClass.isAssignableFrom(Float.class))) {
          newValue = new Float(value.toString());
        } else if ((parameterClass.isAssignableFrom(Double.TYPE)) || (parameterClass.isAssignableFrom(Double.class))) {
          newValue = new Double(value.toString());
        } else if ((parameterClass.isAssignableFrom(Boolean.TYPE)) || (parameterClass.isAssignableFrom(Boolean.class))) {
          String str = value.toString().toLowerCase();

          newValue = ((str.equals("on")) || (str.equals("true")) || (str.equals("yes")) || (str.equals("1"))) ? Boolean.TRUE : Boolean.FALSE;
        }
        else if ((parameterClass.isAssignableFrom(Byte.TYPE)) || (parameterClass.isAssignableFrom(Byte.class))) {
          newValue = new Byte(value.toString());
        } else if ((((parameterClass.isAssignableFrom(Character.TYPE)) || (parameterClass.isAssignableFrom(Character.class)))) && (value.toString().length() > 0)) {
          newValue = new Character(value.toString().charAt(0)); }
    }
    else if (parameterClass.isPrimitive()){
      if (parameterClass.isAssignableFrom(Integer.TYPE))
        newValue = new Integer(String.valueOf(value));
      else if (parameterClass.isAssignableFrom(Short.TYPE))
        newValue = new Short(String.valueOf(value));
      else if (parameterClass.isAssignableFrom(Long.TYPE))
        newValue = new Long(String.valueOf(value));
      else if (parameterClass.isAssignableFrom(Float.TYPE))
        newValue = new Float(String.valueOf(value));
      else if (parameterClass.isAssignableFrom(Double.TYPE))
        newValue = new Double(String.valueOf(value));
      else if (parameterClass.isAssignableFrom(Boolean.TYPE))
        newValue = Boolean.FALSE;
      else if (parameterClass.isAssignableFrom(Byte.TYPE))
        newValue = new Byte(String.valueOf(value));
      else if (parameterClass.isAssignableFrom(Character.TYPE))
        newValue = new Character(' ');
    }
    return (T) newValue;
  }
}
